package com.wwl.controller;

import com.image.util.ImageUtils;
import com.image.util.ImgCompress;
import com.lobby.httpclient.HttpUtils;
import com.lobby.httpclient.SignUtils;
import com.util.DataUtil;
import com.wwl.entity.Location;
import com.wwl.entity.Pay;
import com.wwl.entity.Uploadfile;
import com.wwl.entity.Visitors;
import com.wwl.service.LocationService;
import com.wwl.service.PayService;
import com.wwl.service.UploadfileService;
import com.wwl.service.VisitorsService;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({"/v"})
public class VisitorsController{

  Logger logger = Logger.getLogger(VisitorsController.class);
  String url = "/home/apache-tomcat-7.0.47/webapps/image/grant/";
  @Resource
  LocationService locationService;
  @Resource
  UploadfileService uploadfileService;
  @Resource
  VisitorsService visitorsService;
  @Resource
  PayService payService;
  DataUtil d = new DataUtil();
  
  @RequestMapping(value={"/add"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  public String add(@RequestParam(value="filepath", required=false) MultipartFile file, HttpServletRequest request, Visitors visitors)throws Exception{
    String fileName = file.getOriginalFilename();
    String index = fileName.substring(fileName.lastIndexOf("."));
    String username = request.getParameter("name");
    String ydetailed = request.getParameter("ydetailed");
    String yaddress = request.getParameter("yaddress");
    String relationship = request.getParameter("relationship");
    String userid = request.getParameter("moblie");
    String yphone = request.getParameter("yphone");
    Date data = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    String newData = dateFormat.format(data);
    String name = newData + index;
    File targetFile = new File(this.url + name);
    if (!targetFile.exists()) {
      targetFile.mkdirs();
    }
    try{
      file.transferTo(targetFile);
    }catch (Exception e){
      e.printStackTrace();
    }
    try {
      this.logger.info("前端请求图片名:" + name);
      BufferedImage src = ImageIO.read(targetFile);
      BufferedImage bi = null;
      if (src != null){
        int angel = ImageUtils.getRotateAngleForPhoto(this.url, name);
        if (angel == 0){
          bi = src;
          ImgCompress.setFile(this.url + name);
          this.logger.info("开始：" + new Date().toLocaleString());
          ImgCompress imgCom = new ImgCompress(this.url + name);
          imgCom.resizeFix(400, 400);
          this.logger.info("结束：" + new Date().toLocaleString());
        }else{
          int src_width = src.getWidth(null);
          int src_height = src.getHeight(null);
          Rectangle rect_des = ImageUtils.CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
          bi = new BufferedImage(rect_des.width, rect_des.height, 1);
          Graphics2D g2 = bi.createGraphics();
          g2.translate((rect_des.width - src_width) / 2, 
            (rect_des.height - src_height) / 2);
          g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
          g2.drawImage(src, null, null);
        }
      }else{
        this.logger.info("图片：" + name + "为空");
      }
    }catch (Exception e){
      e.printStackTrace();
    }
    visitors.setYimageurl("https://wwl.ycws.cc/image/grant/" + name);
    visitors.setYname(username);
    visitors.setYphone(yphone);
    visitors.setYaddress(yaddress);
    visitors.setYunitdoor(ydetailed);
    visitors.setRelationship(relationship);
    visitors.setYcreatetime(DataUtil.data1());
    visitors.setYupdatetime(DataUtil.data1());
    visitors.setState(DataUtil.data3(1));
    visitors.setYindate("1");
    visitors.setUserid(userid);
    try{
      this.visitorsService.insert(visitors);
    }catch (Exception e){
      this.logger.info("添加授权人数失败");
    }
    return "redirect:/v/grant?userid=" + userid;
  }
  
  @RequestMapping(value={"/update"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  public String update(@RequestParam(value="filepath", required=false) MultipartFile file, HttpServletRequest request, Visitors visitors)throws Exception{
    String fileName = file.getOriginalFilename();
    String index = fileName.substring(fileName.lastIndexOf("."));
    String username = request.getParameter("name");
    String dong = request.getParameter("dong");
    String relationship = request.getParameter("relationship");
    String yid = request.getParameter("yid");
    String userid = request.getParameter("moblie");
    String yphone = request.getParameter("yphone");
    int Iyid = Integer.parseInt(yid);
    Date data = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    String newData = dateFormat.format(data);
    String name = newData + index;
    File targetFile = new File(this.url + name);
    if (!targetFile.exists()) {
      targetFile.mkdirs();
    }
    try{
      file.transferTo(targetFile);
    }catch (Exception e){
      e.printStackTrace();
    }
    try{
      this.logger.info("前端请求图片名:" + name);
      BufferedImage src = ImageIO.read(targetFile);
      BufferedImage bi = null;
      if (src != null){
        int angel = ImageUtils.getRotateAngleForPhoto(this.url, name);
        if (angel == 0){
          bi = src;
          ImgCompress.setFile(this.url + name);
          this.logger.info("开始：" + new Date().toLocaleString());
          ImgCompress imgCom = new ImgCompress(this.url + name);
          imgCom.resizeFix(400, 400);
          this.logger.info("结束：" + new Date().toLocaleString());
        }else{
          int src_width = src.getWidth(null);
          int src_height = src.getHeight(null);
          Rectangle rect_des = ImageUtils.CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
          bi = new BufferedImage(rect_des.width, rect_des.height, 1);
          Graphics2D g2 = bi.createGraphics();
          g2.translate((rect_des.width - src_width) / 2, 
            (rect_des.height - src_height) / 2);
          g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
          g2.drawImage(src, null, null);
        }
      }else{
        this.logger.info("图片：" + name + "为空");
      }
    }catch (Exception e){
      e.printStackTrace();
    }
    visitors.setYimageurl("https://wwl.ycws.cc/image/grant/" + name);
    visitors.setYname(username);
    visitors.setYphone(yphone);
    visitors.setYunitdoor(dong);
    visitors.setRelationship(relationship);
    visitors.setYid(Integer.valueOf(Iyid));
    visitors.setYupdatetime(DataUtil.data1());
    try{
      this.visitorsService.updateByPrimaryKeySelective(visitors);
    }catch (Exception e){
      this.logger.info("修改授权人员信息失败");
    }
    return "redirect:/v/grant?userid=" + userid;
  }
  
  @RequestMapping({"/grant"})
  public String grant(Visitors visitors, Pay pay, ModelMap map)throws Exception{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    visitors.setUserid(visitors.getUserid());
    List<Visitors> list = this.visitorsService.countC(visitors);
    Date d2;
    for (Visitors v : list){
      v.setYcreatetime(v.getYcreatetime().substring(0, 10));
      v.setState(v.getState().substring(0, 4) + "-" + v.getState().substring(4, 6) + "-" + v.getState().substring(6, 8));
      Date d1 = sdf.parse(DataUtil.data5());
      d2 = sdf.parse(v.getState());
      if (d1.compareTo(d2) == -1) {
        v.setYindate("");
      } else {
        v.setYindate("授权已经过期,请点击前往购买");
      }
    }
    int available = 0;
    pay.setUserid(visitors.getUserid());
    List<Pay> num = this.payService.sumN(pay);
    for (Pay p :num) {
      available = p.getNumber().intValue() + available;
    }
    visitors.setUserid(visitors.getUserid());
    int existence = list.size();
    map.addAttribute("available", Integer.valueOf(available));
    map.addAttribute("existence", Integer.valueOf(existence));
    map.addAttribute("list", list);
    map.addAttribute("moblie", visitors.getUserid());
    map.addAttribute("yphone", visitors.getYphone());
    return "csh/rightUnit";
  }
  
  @RequestMapping({"/show"})
  public String show(int id, String yphone, ModelMap map){
    Visitors visitors = this.visitorsService.show(id);
    map.addAttribute("visitors", visitors);
    map.addAttribute("yphone", yphone);
    return "csh/rightInformationUpdate";
  }
  
  @ResponseBody
  @RequestMapping({"/count"})
  public String count(Visitors visitors, Pay pay){
    visitors.setUserid(visitors.getUserid());
    List<Visitors> list = this.visitorsService.countC(visitors);
    int available = 0;
    pay.setUserid(visitors.getUserid());
    List<Pay> num = this.payService.sumN(pay);
    for (Pay p : num) {
      available = p.getNumber().intValue() + available;
    }
    if (list.size() == available) {
      return "0";
    }
    return "1";
  }
  
  @RequestMapping({"/renew"})
  public String renew(int id, String yphone, String userid, ModelMap modelMap){
    this.logger.info("到期续费");
    modelMap.addAttribute("yid", Integer.valueOf(id));
    modelMap.addAttribute("yphone", yphone);
    modelMap.addAttribute("userid", userid);
    return "csh/renew";
  }
  
  @ResponseBody
  @RequestMapping({"/buy"})
  public String buy(HttpServletRequest request, Pay pay, Uploadfile uploadfile, ModelMap map){
    String yid = request.getParameter("yid");
    String moblie = request.getParameter("moblie");
    String yphone = request.getParameter("yphone");
    String year = request.getParameter("year");
    String url = "https://openapi.colourlife.com/v1/gfjg/pay/unifiedorder";
    uploadfile.setUserid(moblie);
    Uploadfile upload = this.uploadfileService.userid(uploadfile);
    Location moeny = this.locationService.moeny(upload.getYaddress());
    if (moeny.getChargingstatus().equals("1")) {
      return "1";
    }
    int Imoeny = Integer.parseInt(moeny.getMoeny());
    int years = Integer.parseInt(year);
    int total = years * Imoeny;
    String allTotal = String.valueOf(total);
    Map<String, String> testParam = new HashMap();
    testParam.put("business_uuid", "e3ccf625-ee0e-44a4-b138-fa02859dea04");
    testParam.put("device_info", "CZYAPP");
    testParam.put("open_id", moblie);
    testParam.put("mobile", yphone);
    testParam.put("attach", year + "attachend" + yid + "yidend");
    testParam.put("nonce_str", DataUtil.getRandomString(40));
    testParam.put("body", "eanquan");
    testParam.put("detail", "123");
    testParam.put("out_trade_no", this.d.data());
    testParam.put("total_fee", allTotal);
    testParam.put("meal_total_fee", allTotal);
    testParam.put("spbill_create_ip", "120.26.112.214");
    testParam.put("notify_url", "https://wwl.ycws.cc/h5/v/Notify");
    testParam.put("trade_type", "JSAPI");
    testParam.put("scene_info", "1000");
    testParam.put("sign", "397b9020a9dcf696466e8df24295bd73");
    testParam.put("ts", "1513996623");
    testParam.put("appID", "ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED");
    testParam.put("signature", SignUtils.getSignature(testParam));
    String md5 = SignUtils.getSignature(testParam);
    this.logger.info("统一下单接口,生成md5:" + md5);
    String param = SignUtils.buildParams(testParam);
    this.logger.info("请求参数:" + param);
    String responseStr = HttpUtils.sendPost(url, param);
    new JSONObject();
    JSONObject json = JSONObject.fromObject(responseStr);
    return json.toString();
  }
  
  @RequestMapping({"/Notify"})
  @ResponseBody
  public String Notify(HttpServletRequest request)throws Exception{
    BufferedReader reader = null;
    reader = request.getReader();
    System.out.println(reader);
    String line = "";
    String xmlString = null;
    StringBuffer inputString = new StringBuffer();
    while ((line = reader.readLine()) != null) {
      inputString.append(line);
    }
    xmlString = inputString.toString();
    if (xmlString != null){
      this.logger.info("支付回调地址,接收到的数据如下:" + xmlString);
      String trade_state = "trade_state";
      String s2 = xmlString.substring(xmlString.indexOf(trade_state), xmlString.indexOf(trade_state) + trade_state.length() + 2);
      String s3 = s2.substring(12, 13);
      this.logger.info("订单状态(2,3)为交易成功,其余失败:" + s3);
      if ((s3.equals("2")) || (s3.equals("3"))){
        this.logger.info("交易成功");
        String Syear = xmlString.substring(xmlString.indexOf("attach") + "attach=".length(), xmlString.indexOf("attachend"));
        String id = xmlString.substring(xmlString.indexOf("attachend") + "attachend".length(), xmlString.indexOf("yidend"));
        int v_id = Integer.parseInt(id);
        int years = Integer.parseInt(Syear);
        Visitors v = this.visitorsService.show(v_id);
        int year = Integer.parseInt(v.getState().substring(0, 4));
        int i_year = year + years;
        String s_year = String.valueOf(i_year);
        Visitors visitors = new Visitors();
        visitors.setYid(Integer.valueOf(v_id));
        visitors.setState(s_year + v.getState().substring(4, 8));
        visitors.setYupdatetime(DataUtil.data1());
        try{
          this.visitorsService.updateByPrimaryKeySelective(visitors);
          this.logger.info("续费成功");
        }catch (Exception e){
          this.logger.info("续费失败");
        }
        return "SUCCESS";
      }
      this.logger.info("交易失败");
      return "FAIL";
    }
    this.logger.info("支付回调地址,接收到的数据如下:" + xmlString);
    return "FAIL";
  }
  
  @RequestMapping({"/returning"})
  public String returning(ModelMap modelMap, HttpServletRequest request){
    String openid = request.getParameter("moblie");
    String phone = request.getParameter("yphone");
    this.logger.info("续费成功返回界面");
    this.logger.info(openid);
    this.logger.info(phone.substring(0, 11));
    return "redirect:/p/success?userid=" + openid + "&yphone=" + phone.substring(0, 11);
  }
}
